<template>
  <div class="login">
    <div>
      <el-form :model="formState" label-width="120px">
        <el-form-item label="用户名：">
          <el-input v-model="formState.user" />
        </el-form-item>

        <!-- &#12288;  == 一个中文宽度  半个中文宽度占位符：“&ensp;”。-->
        <el-form-item label="密&#12288;码：">
          <el-input v-model="formState.pass" type="password" />
        </el-form-item>
      </el-form>

      <div class="denglu">
        <el-button type="primary" @click="clickLogin">登录</el-button>
      </div>
    </div>
  </div>
</template>
<script setup>
import { getCurrentInstance, onBeforeMount, onMounted, reactive } from "vue";

import { ElMessage } from "element-plus";

import { useRouter } from "vue-router";
import { getLogin } from "../request/api.js";
const router = useRouter();

import { useCounterStore } from "@/store/counter";

const counter = useCounterStore(); //状态管理

const formState = reactive({
  user: "总经理",
  pass: "123456789",
});

const clickLogin = () => {
  getLogin().then((res) => {
    console.log(res, "res");
    if (res.data) {
      let userLength =
        res.data.filter((item) => item.username == formState.user).length !== 0;
      let passLength =
        res.data.filter((item) => item.password == formState.pass).length !== 0;

      if (userLength && passLength) {
        const TOKEN = res.data.find(
          (obj) =>
            obj.username === formState.user && obj.password === formState.pass
        );
        console.log(TOKEN, "TOKEN");

        // 把名字放到状态管理里
        counter.SetUserInfo(formState.user);

        localStorage.setItem("TOKEN", TOKEN.token);
        router.push({
          name: "Home",
        });
      } else {
        ElMessage({
          showClose: true,
          message: "账号或密码错误！",
          type: "error",
        });
      }
    }
  });
};

onMounted(() => {});

const { proxy } = getCurrentInstance();
const emits = defineEmits([]);
const props = defineProps({});
const state = reactive({});
onBeforeMount(() => {});

defineExpose({ state });
</script> 
<style lang="scss" scoped>
.login {
  background: url(../assets/bg.png);
  height: 100%;
  width: 100%;
  display: flex;
  //   justify-content: center;
  align-items: center;
  .denglu {
    display: flex;
    justify-content: center;
    //   align-items: center;
  }
}
</style>